package dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import dao.UsersDao;
import entity.Users;
import util.PageUtil;

public class UsersDaoImpl extends HibernateDaoSupport implements UsersDao {

	@Override
	public Users findByName(String name) {
		List<Users> list = getHibernateTemplate().find("from Users where name = ? ", name);
		
		return (list != null && list.size() > 0) ? list.get(0) : null;
	}
	@Override
	public int findCount(PageUtil<Users> page) {
		String name = "";
		Map<String, Object> cond = page.getCond();
		if(cond != null && cond.get("name") != null){
			String[] params = (String[]) cond.get("name"); 
			if(params.length > 0){
				name = params[0];
			}
		}
		List<Long> count = getHibernateTemplate().find("select count(u) from Users u where name like ?",
						"%"+name+"%");
		return count.get(0).intValue();
	}
	@Override
	public List<Users> findPage(PageUtil<Users> page) {
		String name = "";
		Map<String, Object> cond = page.getCond();
		if(cond != null && cond.get("name") !=null){
			String[] params = (String[]) cond.get("name");
			if(params.length > 0){
				name = params[0];
			}
		}
		DetachedCriteria dc = DetachedCriteria.forClass(Users.class);
		dc.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
		List<Users> list = getHibernateTemplate().findByCriteria(dc, page.getOffset(), page.getPageSize());
		return list;
	}
	@Override
	public int updatePwd(Users u) {
		// TODO Auto-generated method stub
		getHibernateTemplate().update(u);
		return 1;
	}
}
